package DataStructure;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class HashtableTest {
    
    public static void main(String[] args) {
        
          // Create a hash map
      Hashtable<String,Double> balance = new Hashtable<String,Double>();
      Enumeration names;
      String str;
      double bal;

      balance.put("Zara", 3434.34);
      balance.put("Mahnaz", 123.22);
      balance.put("Ayan", 1378.00);
      balance.put("Daisy", 99.22);
      balance.put("Qadir", -19.08);

      System.out.println("hashCode: " + balance.hashCode());//Map的散列代码值 哈希码值

      // Show all balances in hash table.
      names = balance.keys();
      while(names.hasMoreElements()) {
         str = (String) names.nextElement();
         System.out.println(str + ": " +
         balance.get(str));
      }
      System.out.println();
      // Deposit 1,000 into Zara's account
      bal = ((Double)balance.get("Zara")).doubleValue();
      balance.put("Zara", bal+1000);
      System.out.println("Zara's new balance: " +
      balance.get("Zara"));


      System.out.println("遍历 Map");
      // 第一种：普遍使用，二次取值
      System.out.println("通过Map.keySet遍历key和value：");
      for (String key : balance.keySet()) {
          System.out.println("key= " + key + " and value= " + balance.get(key));
      }

      // 第二种
      System.out.println("通过Map.entrySet使用iterator遍历key和value：");
      Iterator<Map.Entry<String, Double>> it = balance.entrySet().iterator();
      while (it.hasNext()) {
          Map.Entry<String, Double> entry = it.next();
          System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }

      // 第三种：推荐，尤其是容量大时
      System.out.println("通过Map.entrySet遍历key和value");
      for (Map.Entry<String, Double> entry : balance.entrySet()) {
          System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }

      // 第四种
      System.out.println("通过Map.values()遍历所有的value，但不能遍历key");
      for (double v : balance.values()) {
          System.out.println("value= " + v);
      }
    }
}
